//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer } from 'mobx-react';
import type { ImageGroupInfo, ImageGroupPerm, ImageGroupMemberList } from "@/api/seaotter/image_group";
import { create as create_group, update_perm as update_group_perm } from "@/api/seaotter/image_group";
import { Checkbox, Form, Input, message, Modal, Select, Space } from "antd";
import { useSeaOtterStores } from "../store";
import { get_session } from "@/api/user";
import { request } from "@/utils/request";
import { gen_access_token } from "@/api/project_server";
import { list_name as list_secret_name } from "@/api/seaotter/auth_secret";
import UserPhoto from "@/components/Portrait/UserPhoto";

const GroupNameRegex = /^[_0-9a-zA-Z]+$/;

interface EditGroupModalProps {
    imageGroup?: ImageGroupInfo;
    onCancel: () => void;
    onOk: () => void;
}

const EditGroupModal = (props: EditGroupModalProps) => {
    const appStore = useSeaOtterStores();

    const [groupName, setGroupName] = useState(props.imageGroup?.group_name ?? "");
    const [permInfo, setPermInfo] = useState<ImageGroupPerm>(props.imageGroup?.perm_info ?? ({
        public_group: false,
        member_perm: {},
        pull_secret_name_list: [],
        push_secret_name_list: [],
    }));
    const [secNameList, setSecNameList] = useState<string[]>([]);
    const [hasChange, setHasChange] = useState(false);


    const createGroup = async () => {
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0 || groupName == "") {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));

        let prjPermInfo: null | undefined | ImageGroupMemberList = permInfo.member_perm[appStore.projectId];
        if (prjPermInfo == undefined || prjPermInfo == null) {
            prjPermInfo = {
                member_user_id_for_view: [],
                member_user_id_for_remove: [],
            };
            permInfo.member_perm[appStore.projectId] = prjPermInfo;
        }

        await request(create_group(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
            group_name: groupName,
            perm_info: permInfo,
        }));
        message.info("创建成功");
        props.onOk();
    };

    const updateGroupPerm = async () => {
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0 || groupName == "") {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));

        let prjPermInfo: null | undefined | ImageGroupMemberList = permInfo.member_perm[appStore.projectId];
        if (prjPermInfo == undefined || prjPermInfo == null) {
            prjPermInfo = {
                member_user_id_for_view: [],
                member_user_id_for_remove: [],
            };
            permInfo.member_perm[appStore.projectId] = prjPermInfo;
        }

        await request(update_group_perm(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
            group_name: groupName,
            perm_info: permInfo,
        }));
        message.info("更新成功");
        props.onOk();
    };

    const checkGroupNameValid = (): boolean => {
        if (groupName == "") {
            return false;
        }
        return GroupNameRegex.test(groupName);
    };

    const checkValid = (): boolean => {
        if (!hasChange) {
            return false;
        }
        if (!checkGroupNameValid()) {
            return false;
        }
        const prjPermInfo: null | undefined | ImageGroupMemberList = permInfo.member_perm[appStore.projectId];
        if (prjPermInfo == undefined || prjPermInfo == null) {
            return false;
        }
        return true;
    };

    const loadSecNameList = async () => {
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0) {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));

        const res = await request(list_secret_name(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
        }));
        setSecNameList(res.name_list);
    };

    useEffect(() => {
        if (appStore.remoteServer != null) {
            loadSecNameList();
        }
    }, [appStore.remoteServer]);

    return (
        <Modal open title={props.imageGroup == undefined ? "创建镜像分组" : "更新镜像分组"} mask={false}
            okText={props.imageGroup == undefined ? "创建" : "更新"} okButtonProps={{ disabled: !checkValid() }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onCancel();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                if (props.imageGroup == undefined) {
                    createGroup();
                } else {
                    updateGroupPerm();
                }
            }}>
            <Form labelCol={{ span: 4 }}>
                <Form.Item label="分组名称" help="只能使用数字字母和下划线">
                    <Input disabled={props.imageGroup != undefined} value={groupName} onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setGroupName(e.target.value.trim());
                    }} status={checkGroupNameValid() ? undefined : "error"}
                        placeholder="请输入镜像分组名称" />
                </Form.Item>
                <Form.Item label="公开访问" help="打开后所有成员都能访问镜像分组">
                    <Checkbox checked={permInfo.public_group} onChange={e => {
                        e.stopPropagation();
                        setPermInfo({
                            ...permInfo,
                            public_group: e.target.checked,
                        });
                        setHasChange(true);
                    }} />
                </Form.Item>
                {permInfo.public_group == false && (
                    <Form.Item label="访问权限" help="设置可访问镜像分组的成员">
                        <Select mode="multiple" value={permInfo.member_perm[appStore.projectId]?.member_user_id_for_view ?? []}
                            onChange={values => {
                                let prjPermInfo: null | undefined | ImageGroupMemberList = permInfo.member_perm[appStore.projectId];
                                if (prjPermInfo == undefined || prjPermInfo == null) {
                                    prjPermInfo = {
                                        member_user_id_for_view: [],
                                        member_user_id_for_remove: [],
                                    };
                                    permInfo.member_perm[appStore.projectId] = prjPermInfo;
                                }
                                permInfo.member_perm[appStore.projectId].member_user_id_for_view = values;
                                setPermInfo({
                                    ...permInfo,
                                });
                                setHasChange(true);
                            }}>
                            {appStore.projectMemberList.map(prjMember => (
                                <Select.Option key={prjMember.member_user_id} value={prjMember.member_user_id}>
                                    <Space>
                                        <UserPhoto logoUri={prjMember.logo_uri} style={{ width: "20px", height: "20px", borderRadius: "10px" }} />
                                        {prjMember.display_name}
                                    </Space>
                                </Select.Option>
                            ))}
                        </Select>
                    </Form.Item>
                )}
                <Form.Item label="删除权限" help="设置可删除镜像的成员。只有管理员才能删除镜像分组！">
                    <Select mode="multiple" value={permInfo.member_perm[appStore.projectId]?.member_user_id_for_remove ?? []}
                        onChange={values => {
                            let prjPermInfo: null | undefined | ImageGroupMemberList = permInfo.member_perm[appStore.projectId];
                            if (prjPermInfo == undefined || prjPermInfo == null) {
                                prjPermInfo = {
                                    member_user_id_for_view: [],
                                    member_user_id_for_remove: [],
                                };
                                permInfo.member_perm[appStore.projectId] = prjPermInfo;
                            }
                            permInfo.member_perm[appStore.projectId].member_user_id_for_remove = values;
                            setPermInfo({
                                ...permInfo,
                            });
                            setHasChange(true);
                        }}>
                        {appStore.projectMemberList.map(prjMember => (
                            <Select.Option key={prjMember.member_user_id} value={prjMember.member_user_id}>
                                <Space>
                                    <UserPhoto logoUri={prjMember.logo_uri} style={{ width: "20px", height: "20px", borderRadius: "10px" }} />
                                    {prjMember.display_name}
                                </Space>
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item label="拉取密钥" help="可用户pull的密钥列表">
                    <Select mode="multiple" value={permInfo.pull_secret_name_list} onChange={values => {
                        setPermInfo({
                            ...permInfo,
                            pull_secret_name_list: values,
                        });
                        setHasChange(true);
                    }}>
                        {secNameList.map(secName => (
                            <Select.Option key={secName} value={secName}>{secName}</Select.Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item label="推送密钥" help="可用于push的密钥列表">
                    <Select mode="multiple" value={permInfo.push_secret_name_list} onChange={values => {
                        setPermInfo({
                            ...permInfo,
                            push_secret_name_list: values,
                        });
                        setHasChange(true);
                    }}>
                        {secNameList.map(secName => (
                            <Select.Option key={secName} value={secName}>{secName}</Select.Option>
                        ))}
                    </Select>
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default observer(EditGroupModal);